/**
 * Copyright &copy; 2017-2020 <a href="http://www.fosung.com/">FosungFrame</a> All rights reserved.
 */
package com.fosung.frame.modules.life.web;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fosung.frame.common.config.Global;
import com.fosung.frame.common.persistence.Page;
import com.fosung.frame.common.utils.StringUtils;
import com.fosung.frame.common.web.BaseController;
import com.fosung.frame.modules.checkinfos.entity.Checkinfos;
import com.fosung.frame.modules.checkinfos.service.CheckinfosService;
import com.fosung.frame.modules.life.entity.OrganizeLife;
import com.fosung.frame.modules.life.entity.OrganizeLifeType;
import com.fosung.frame.modules.life.service.OrganizeLifeService;
import com.fosung.frame.modules.life.service.OrganizeLifeTypeService;
import com.fosung.frame.modules.partysinfo.entity.PartysInfo;
import com.fosung.frame.modules.partysinfo.service.PartysInfoService;
import com.fosung.frame.modules.sys.utils.UserUtils;

/**
 * 组织生活管理Controller
 * 
 * @author zhangfn
 * @version 2017-08-29
 */
@Controller
@RequestMapping(value = "${adminPath}/life/organizeLife")
public class OrganizeLifeController extends BaseController {

	@Autowired
	private OrganizeLifeService organizeLifeService;
	@Autowired
	private OrganizeLifeTypeService organizeLifeTypeService;
	@Autowired
	private CheckinfosService checkinfosService;
	@Autowired
	private PartysInfoService partysInfoService;

	@ModelAttribute
	public OrganizeLife get(@RequestParam(required = false) String id) {
		OrganizeLife entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = organizeLifeService.get(id);
		}
		if (entity == null) {
			entity = new OrganizeLife();
		}
		return entity;
	}

	@RequiresPermissions("life:organizeLife:view")
	@RequestMapping(value = { "list", "" })
	public String list(OrganizeLife organizeLife, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		organizeLife.setColumn25("0");
		organizeLife.setOrganizationid(UserUtils.getUser().getOffice().getId());
		Page<OrganizeLife> page = organizeLifeService.findPage(new Page<OrganizeLife>(request, response), organizeLife);

		// 给首页组织生活分类下拉框赋值
		OrganizeLifeType type = new OrganizeLifeType();
		type.setDelFlag("0");
		type.setHasChildren("0");
		type.setOrgId(UserUtils.getUser().getOffice().getId());
		List<OrganizeLifeType> organizeLifeTypes = organizeLifeTypeService.findList(type);
		model.addAttribute("organizeLifeTypes", organizeLifeTypes);
		// 因为组织生活分类可能包括多个，这里先spilt再单独查询拼成字符串显示到前台list

		List<OrganizeLife> olList = page.getList();

		if (olList.size() > 0) {
			for (int i = 0; i < olList.size(); i++) {
				StringBuffer typeNames = new StringBuffer();
				OrganizeLife o = olList.get(i);
				if (o.getTypeids() != null && !o.getTypeids().equals("")) {
					String[] types = o.getTypeids().split(",");

					if (types != null && types.length > 0) {
						for (String s : types) {
							// 循环遍历数组中元素，添加到StringBuilder 对象中
							String t = organizeLifeTypeService.get(s).getTypename();
							typeNames.append(t + ",");
						}
					}
					if (typeNames.length() > 0) {
						// 调用字符串的deleteCharAt()方法,删除最后一个多余的逗号
						typeNames.deleteCharAt(typeNames.length() - 1);
					}

				}
				o.setTypeids(typeNames.toString());
			}
		}

		model.addAttribute("page", page);
		return "modules/life/organizeLifeList";
	}

	@RequiresPermissions("life:organizeLife:view")
	@RequestMapping(value = "form")
	public String form(OrganizeLife organizeLife, Model model) throws ParseException, UnsupportedEncodingException {
		// 循环获取审批意见，然后赋值
		Checkinfos ci = new Checkinfos();
		ci.setOrganizeLifeId(organizeLife.getId());
		List<Checkinfos> listCheckinfos = checkinfosService.findList(ci);
		if (listCheckinfos.size() > 0) {
			String str = "";
			for (Checkinfos s : listCheckinfos) {
				Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK)
						.parse(s.getCreateDate().toString());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				String sDate = sdf.format(date);

				str += "审核时间：" + sDate + ",审核人：" + s.getShName() + ",审核意见:" + s.getApproveContent() + "\n";
			}
			organizeLife.setShyj(str);
		}
		//
		List<OrganizeLifeType> listStr = new ArrayList();
		if (organizeLife.getTypeids() != null && !organizeLife.getTypeids().equals("")) {
			String[] types = organizeLife.getTypeids().split(",");

			if (types != null && types.length > 0) {
				for (String s : types) {
					// 循环遍历数组中元素，添加到StringBuilder 对象中
					OrganizeLifeType o = new OrganizeLifeType();
					String t = organizeLifeTypeService.get(s).getTypename();
					o.setTypename(t);
					listStr.add(o);
				}
				model.addAttribute("listStr", listStr);
			}

		}
		Map<Integer, String> yyzlmap = new HashMap<Integer, String>();
		if (organizeLife.getYyzl() != null && !organizeLife.getYyzl().equals("")) {
			String[] yyzl = organizeLife.getYyzl().split("\\|");
			for (int i = 1; i < yyzl.length; i++) {
				yyzlmap.put(i, yyzl[i]);
			}
			model.addAttribute("yyzlmap", yyzlmap);
		}

		Map<String, String> fjmap = new HashMap<String, String>();
		if (organizeLife.getFujian() != null && !organizeLife.getFujian().equals("")) {
			String[] fj = organizeLife.getFujian().split("\\|");
			for (int i = 1; i < fj.length; i++) {

				File tempFile = new File(fj[i].trim());
				String fileName = tempFile.getName();
				fjmap.put(fj[i], URLDecoder.decode(fileName, "utf-8"));
			}
			model.addAttribute("fjmap", fjmap);
		}

		model.addAttribute("organizeLife", organizeLife);
		return "modules/life/organizeLifeForm";
	}

	@RequiresPermissions("life:organizeLife:edit")
	@RequestMapping(value = "save")
	public String save(OrganizeLife organizeLife, Model model, RedirectAttributes redirectAttributes)
			throws ParseException, UnsupportedEncodingException {
		if (!beanValidator(model, organizeLife)) {
			return form(organizeLife, model);
		}
		organizeLife.setColumn25("0");
		organizeLife.setShstate("1");
		organizeLifeService.save(organizeLife);
		addMessage(redirectAttributes, "保存组织生活管理成功");
		return "redirect:" + Global.getAdminPath() + "/life/organizeLife/?repage";
	}

	@RequiresPermissions("life:organizeLife:edit")
	@RequestMapping(value = "delete")
	public String delete(OrganizeLife organizeLife, RedirectAttributes redirectAttributes) {
		organizeLifeService.delete(organizeLife);
		addMessage(redirectAttributes, "删除组织生活管理成功");
		return "redirect:" + Global.getAdminPath() + "/life/organizeLife/?repage";
	}

	@RequestMapping(value = "queryListByIds")
	public String queryListByIds(OrganizeLife organizeLife, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Page<OrganizeLife> page = organizeLifeService.findPage(new Page<OrganizeLife>(request, response), organizeLife);

		// 给首页组织生活分类下拉框赋值
		OrganizeLifeType type = new OrganizeLifeType();
		type.setDelFlag("0");
		List<OrganizeLifeType> organizeLifeTypes = organizeLifeTypeService.findList(type);
		model.addAttribute("organizeLifeTypes", organizeLifeTypes);
		// 因为组织生活分类可能包括多个，这里先spilt再单独查询拼成字符串显示到前台list

		List<OrganizeLife> olList = page.getList();

		if (olList.size() > 0) {
			for (int i = 0; i < olList.size(); i++) {
				StringBuffer typeNames = new StringBuffer();
				OrganizeLife o = olList.get(i);
				if (o.getTypeids() != null && !o.getTypeids().equals("")) {
					String[] types = o.getTypeids().split(",");

					if (types != null && types.length > 0) {
						for (String s : types) {
							// 循环遍历数组中元素，添加到StringBuilder 对象中
							String t = organizeLifeTypeService.get(s).getTypename();
							typeNames.append(t + ",");
						}
					}
					if (typeNames.length() > 0) {
						// 调用字符串的deleteCharAt()方法,删除最后一个多余的逗号
						typeNames.deleteCharAt(typeNames.length() - 1);
					}

				}
				o.setTypeids(typeNames.toString());
			}
		}

		model.addAttribute("page", page);
		return "modules/life/organizeLifeList";
	}

	// 判断当前支部有没有关闭
	@ResponseBody
	@RequestMapping(value = "/checkOrgSatate", method = RequestMethod.GET)
	public Map<String, String> checkOrgSatate(RedirectAttributes redirectAttributes) {
		Map<String, String> map = new HashMap<String, String>();

		PartysInfo p = partysInfoService.getByOrgid(UserUtils.getUser().getOffice().getId());
		if (p == null) {
			map.put("type", "error");
			map.put("msg", "当前支部已关闭！");
		} else {
			map.put("type", "success");		
		}

		return map;
	}

}